<template>
    <div class="">
        <el-form :inline="true">
            <div style="display: flex; justify-content: space-between;">
                <div>
                    <el-form-item label="状态：">
                        <el-select v-model="state" placeholder="状态">
                            <el-option key="0" label="全部" value="0" />
                            <el-option key="1" label="已上架" value="1" />
                            <el-option key="2" label="已下架" value="2" />
                            <el-option key="3" label="已出售" value="3" />
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="init">查询</el-button>
                    </el-form-item>
                </div>
                <div>
                    <el-button type="primary" @click="onVisible(1)">新增</el-button>
                </div>
            </div>
        </el-form>
        <el-table v-loading="listLoading" :data="tableData" border style="width: 100%">
            <el-table-column prop="id" label="属性ID" width="80" align="center" />
            <el-table-column prop="goodspicurl" label="图片" width="120" align="center">
                <template slot-scope="{row}">
                    <el-image style="width: 60px; height: 60px" :src="row.goodspicurl.split(',')[0]"
                        :preview-src-list="row.goodspicurl.split(',')" />
                </template>
            </el-table-column>
            <el-table-column prop="goodsname" label="属性名称" align="center" />
            <el-table-column prop="price" label="价格" width="100" align="center" />
            <el-table-column prop="costprice" label="成本价" width="100" align="center" />
            <el-table-column prop="goodsnum" label="数量/重量" width="100" align="center" />
            <el-table-column prop="goodsunit" label="单位" width="100" align="center" />
            <el-table-column prop="ljfcount" label="返利积分" width="110" align="center" />
            <el-table-column prop="card1Count" label="获得体验券数量" align="center" />
            <el-table-column prop="card2Count" label="获得次卡数量" align="center" />
            <el-table-column prop="stock" label="库存" width="100" align="center" />
            <el-table-column prop="state" label="状态" width="80" align="center">
                <template slot-scope="scope">
                    <el-tag v-if="scope.row.state == 1">已上架</el-tag>
                    <el-tag v-if="scope.row.state == 2" type="danger">已下架</el-tag>
                    <el-tag v-if="scope.row.state == 3" type="warning">已出售</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="sort" label="排序" width="80" align="center" />
            <el-table-column label="操作" width="150" align="center">
                <template slot-scope="{row}">
                    <el-button size="mini" type="primary" @click="onVisible(2, row)">编辑</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 新增、编辑 -->
        <el-dialog width="1000px" :close-on-click-modal="false" :title="visibleType == 1 ? '新增' : '编辑'"
            :visible.sync="dialogVisible" @open="openDialog('forms')" @closed="closedDialog">
            <el-form id="forms" ref="forms" :rules="rulesModel" :model="form" label-width="130px"
                style="max-height: 600px;overflow-y: scroll;">
                <div>
                    <el-form-item label="商品图片" prop="goodspicurl">
                        <UploadImageList :existList="picurlsArr" @uploadSuccess="uploadSuccess"
                            @delExist="delExistChange" :isDisplay="dialogVisible" />
                    </el-form-item>
                </div>
                <div>
                </div>
                <el-form-item label="属性名称" prop="goodsname" style="width: 900px;">
                    <el-input v-model="form.goodsname" type="text" placeholder="请输入属性名称" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="价格" prop="price">
                        <el-input v-model="form.price" type="number" placeholder="请输入价格" />
                    </el-form-item>
                    <el-form-item label="成本价" prop="costprice">
                        <el-input v-model="form.costprice" type="number" placeholder="请输入成本价" />
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="数量/重量" prop="goodsnum">
                        <el-input v-model="form.goodsnum" type="number" placeholder="请输入数量/重量" />
                    </el-form-item>
                    <el-form-item label="单位" prop="goodsunit">
                        <el-input v-model="form.goodsunit" type="text" placeholder="请输入单位" />
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="提货返利积分" prop="ljfcount" label-width="200" style="width: 600px;">
                        <div class="flex">
                            <el-input v-model="form.ljfcount" :disabled="this.userInfo.roid == 4"
                                placeholder="请输入提货返利积分" />
                        </div>
                    </el-form-item>
                </div>
                <el-form-item label="获得贡献值" prop="discount" style="width: 900px;">
                    <el-input v-model.number="form.discount" :rows="2" placeholder="请输入获得贡献值" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item label="获得体验券数量" prop="card1Count">
                        <el-input v-model.number="form.card1Count" :rows="2" placeholder="请输入获得体验券数量" />
                    </el-form-item>
                    <el-form-item label="获得次卡数量" prop="card2Count">
                        <el-input v-model.number="form.card2Count" :rows="2" placeholder="请输入获得次卡数量" />
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="消耗币种">
                        <el-select v-model="form.feecoinid" placeholder="请选择币种" clearable>
                            <el-option label="无" :value="0" />
                            <el-option v-for="item in coinList" :label="item.coinname" :value="item.coinid" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="消耗数量">
                        <el-input v-model="form.feejf" type="number" placeholder="请输入消耗数量" />
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="库存" prop="stock">
                        <el-input v-model="form.stock" type="number" placeholder="请输入库存" />
                    </el-form-item>
                    <el-form-item label="排序">
                        <el-input v-model="form.sort" type="number" placeholder="请输入排序" />
                    </el-form-item>
                </div>
                <!-- <el-form-item label="外部链接" style="width: 900px;">
                    <el-input v-model="form.weburl" type="text" placeholder="请输入外部链接" />
                </el-form-item> -->
                <el-form-item label="上架/下架" prop="goodsname">
                    <el-switch v-model="form.state" :active-value="1" :inactive-value="2" />
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button :loading="buttonLoading" type="primary" @click="onEdit(1)">确 定</el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
import { GetGoodsAttr, EditAttr } from '@/api/goods'
import editor from "../../../components/Editor/index.vue"; // 富文本组件
import { formatDate } from '@/utils/index.js'
import { GetEnum, coinlist } from "@/api/ctrls.js";
import { getInfo } from '@/api/sys'
export default {
    name: 'Name',
    components: { editor },
    data() {
        return {
            // 参数
            gid: 0, // 商品id(必传)
            state: "0", // 关键字查询

            coinList: [], // 币种列表

            // 列表
            listLoading: false,// 列表加载中
            tableData: [],
            totalCount: 0,
            PageIndex: 1,
            pageSize: 10,


            // 新增\编辑对话框
            dialogVisible: false,
            buttonLoading: false, // 按钮加载中
            visibleType: "", // 1:新增；2：编辑
            price: 0, // 价格
            form: {}, // 详情实体
            rulesModel: {
                goodspicurl: [
                    { required: true, message: '请上传商品图片', trigger: 'blur' }
                ],
                goodsname: [
                    { required: true, message: '请输入属性名称', trigger: 'blur' }
                ],
                price: [
                    { required: true, message: '请输入价格', trigger: 'blur' }
                ],
                costprice: [
                    { required: true, message: '请输入成本价', trigger: 'blur' }
                ],
                goodsnum: [
                    { required: true, message: '请输入数量/重量', trigger: 'blur' }
                ],
                goodsunit: [
                    { required: true, message: '请输入单位', trigger: 'blur' }
                ],
                discount: [
                    { required: true, message: '请输入贡献值', trigger: 'blur' }
                ],
                ljfcount: [
                    { required: true, message: '请输入提货返利积分', trigger: 'blur' }
                ],
                stock: [
                    { required: true, message: '请输入库存', trigger: 'blur' }
                ],
                card2Count: [{ required: true, message: "请输入获得次卡数量", trigger: "blur" }],
                card1Count: [{ required: true, message: "请输入获得体验券数量", trigger: "blur" }]
            },
            userInfo: {},

            // 上传图片相关
            picurlsArr: [], // 已有图片列表
            uploadImageList: [], // 上传成功后的图片列表
        }
    },
    watch: {
        PageIndex(val) {
            console.log(val)
            this.getData()
        },
        pageSize(val) {
            console.log(val)
            this.getData()
        }
    },
    created() {
        this.gid = this.$route.query.gid || 0
        this.price = this.$route.query.price || 0
    },
    async mounted() {
        this.getData()
        this.GetEnum();
        this.GetCoin();
        this.getInfo();
    },
    methods: {
        /////////////////////////////////////////////////// 初始化 ////////////////////////////////////////////////
        /**列表初始化 */
        async init() {
            this.PageIndex = 1;
            this.getData();
        },
        /**表单参数初始化 */
        initForm() {
            this.form = {
                id: 0,
                gid: this.gid, // 商品id
                price: this.price, // 价格
                costprice: 0, // 成本价
                goodsname: '', // 属性名称
                goodspicurl: '', // 属性图片
                goodsnum: 1, // 数量/重量
                goodsunit: '', // 单位
                discount: 0, // 贡献值
                ljfcount: 0, // 提货返利积分
                weburl: '无', // 外部链接
                state: 1, // 1上架 2下架 3已售
                stock: 1, // 库存
                sort: 0, // 排序
                feecoinid: 1, // 消耗币种
                feejf: 0, // 消耗数量
                card1Count: 0, // 
                card2Count: 0, // 
            };
        },
        /////////////////////////////////////////////////// 弹窗 ////////////////////////////////////////////////////

        /////////////////////// 主对话框  ///////////////////////
        /**
         * 新增/编辑按钮点击
         * @param {*} type 1：新增；2：编辑
         * @param {*} info 操作数据对象
         */
        async onVisible(type, info = {}) {
            this.visibleType = type;

            this.picurlsArr = [];
            this.initForm();

            // 编辑
            if (type === 2) {
                // 获取详情
                this.form = { ...info };
                // 图片列表
                if (this.form.goodspicurl) {
                    const a = this.form.goodspicurl.split(",");
                    a.forEach(item => {
                        this.picurlsArr.push(item);
                    });
                }
            }

            this.dialogVisible = true;
        },
        /**
         * 对话框打开前
         * @param {*} form_id 表单id
         */
        openDialog(form_id) {
            // 滚动条移动到表单顶部
            this.$nextTick(() => {
                document.getElementById(form_id).scrollTop = 0;
            });
        },
        /**对话框关闭结束（新增\编辑） */
        closedDialog() {
            // 清空上传组件图片列表
            this.uploadImageList = [];
            // 移除表单项的校验结果
            this.$refs.forms.clearValidate();
        },
        /////////////////////////////////////////////////// 图片相关 ////////////////////////////////////////////////
        /**
         * 图片上传成功监听
         * @param {*} arr 上传组件成功后的数据列表
         */
        uploadSuccess(arr) {
            console.log('上传成功：', arr)
            this.uploadImageList = arr;
        },
        /**
         * 删除已有图片监听
         * @param {*} arr 删除已有图片后的图片列表
         */
        delExistChange(arr) {
            this.picurlsArr = arr;
            console.log('删除本地图片后：', this.picurlsArr);
        },
        /////////////////////////////////////////////////// 数据请求 ////////////////////////////////////////////////
        /**获取主列表 */
        async getData() {
            this.listLoading = true
            const list = await GetGoodsAttr({
                gid: this.gid,
                state: this.state
            })
            if (list) {
                this.tableData = [];
                list.forEach(element => {
                    this.tableData.push(element)
                })
            }
            console.log('主列表，', list)
            this.listLoading = false
        },
        /**确定提交（新增/编辑） */
        onEdit() {

            // 图片序列化
            const imgarr = [];
            // 本地图片
            if (this.picurlsArr.length > 0) {
                this.picurlsArr.forEach(item => {
                    imgarr.push(item)
                })
            }
            // 新上传图片
            if (this.uploadImageList.length > 0) {
                this.uploadImageList.forEach(item => {
                    imgarr.push(item.url)
                })
            }
            this.form.goodspicurl = imgarr.toString();
            console.log('图片字符串', this.form.goodspicurl);

            // 表单校验
            this.$refs['forms'].validate(async (valid) => {
                if (valid) {
                    this.form.state = Number(this.form.state) || 0
                    this.form.weburl = this.form.weburl || '无'
                    this.form.feecoinid = Number(this.form.feecoinid) || 0;

                    if (this.form.ljfcount < 0) {
                        this.$message({
                            message: "价格不能小于成本价",
                            type: "error"
                        });
                        return;
                    }

                    this.buttonLoading = true
                    try {
                        const { success, msg } = await EditAttr(this.form)
                        this.buttonLoading = false
                        if (success) {
                            this.dialogVisible = false
                            this.getData()
                        }
                        this.$message({
                            message: msg,
                            type: success ? 'success' : 'error'
                        })
                    } catch (error) {
                        this.buttonLoading = false
                    }

                } else {
                    return false
                }
            })
        },
        // 获取枚举
        async GetEnum() {
            const res = await GetEnum();
        },
        // 获取币种
        async GetCoin() {
            const res = await coinlist();
            this.coinList = res;
        },
        /**获取用户信息 */
        async getInfo() {
            const info = await getInfo()
            this.userInfo = info;
            console.log(this.userInfo)
        },
    }
}
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.el-table .warning-row {
    background: oldlace;
}
</style>